<template>
  <div class="app-container active">
    <Header></Header>
    <main class="main-container">
      <!-- Main Content Area -->
      <div class="content-wrapper">
        <!-- Left Sidebar -->
        <aside class="sidebar">
          
          <div class="sidebar-section">
            <div class="sidebar-header">
              <button class="add-conversation-btn" @click="createNewConversation">
                <svg width="16" height="16" viewBox="0 0 28 28" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M9.10999 27C8.92999 27 8.76001 26.96 8.60001 26.9C8.43001 26.83 8.29 26.74 8.16 26.61C8.03 26.49 7.94 26.3499 7.87 26.1899C7.79999 26.0299 7.76001 25.8599 7.76001 25.6899L7.73001 23.04C7.34001 22.98 6.95001 22.8799 6.57001 22.7599C6.19001 26.2299 5.83001 22.48 5.48001 22.29C5.13001 22.1 4.79999 21.88 4.48999 21.63C4.17999 21.39 3.89 21.1199 3.63 20.82C3.37 20.52 3.13999 20.21 2.92999 19.87C2.72999 19.53 2.56001 19.18 2.42001 18.82C2.28001 18.45 2.17001 18.07 2.10001 17.69C2.03001 17.3 2 16.92 2 16.53V9.46995C2 9.03995 2.04 8.61995 2.12 8.19995C2.21 7.77995 2.34 7.36995 2.5 6.96995C2.67 6.57995 2.88 6.19995 3.12 5.84995C3.36 5.48995 3.64001 5.15995 3.95001 4.85995C4.26001 4.55995 4.59999 4.28995 4.95999 4.04995C5.32999 3.80995 5.70999 3.60995 6.10999 3.44995C6.51999 3.27995 6.94 3.15995 7.37 3.07995C7.79999 2.98995 8.23001 2.94995 8.67001 2.94995H13.3C13.46 2.94995 13.61 2.97995 13.76 3.03995C13.9 3.09995 14.03 3.17995 14.14 3.28995C14.25 3.39995 14.33 3.51995 14.39 3.65995C14.45 3.79995 14.48 3.94995 14.48 4.09995C14.48 4.25995 14.45 4.39995 14.39 4.54995C14.33 4.68995 14.25 4.80995 14.14 4.91995C14.03 5.02995 13.9 5.10995 13.76 5.16995C13.61 5.22995 13.46 5.25995 13.3 5.25995H8.67001C8.38001 5.25995 8.09999 5.27995 7.82999 5.33995C7.54999 5.38995 7.27999 5.46995 7.01999 5.57995C6.75999 5.67995 6.50999 5.80995 6.26999 5.96995C6.03999 6.11995 5.82 6.29995 5.62 6.48995C5.42 6.68995 5.23999 6.89995 5.07999 7.12995C4.92999 7.35995 4.78999 7.59995 4.67999 7.85995C4.57999 8.10995 4.49 8.37995 4.44 8.64995C4.38 8.91995 4.35999 9.18995 4.35999 9.46995V16.53C4.35999 16.81 4.38 17.08 4.44 17.36C4.5 17.63 4.58 17.9 4.69 18.16C4.8 18.42 4.93 18.67 5.09 18.9C5.25 19.13 5.43001 19.3499 5.64001 19.5499C5.84001 19.75 6.05999 19.92 6.29999 20.08C6.53999 20.24 6.79 20.37 7.06 20.47C7.32 20.58 7.6 20.66 7.88 20.72C8.16001 20.77 8.44001 20.7999 8.73001 20.7999C8.91001 20.7999 9.08 20.83 9.25 20.9C9.41 20.97 9.55999 21.0599 9.67999 21.18C9.80999 21.3099 9.91001 21.45 9.98001 21.61C10.05 21.77 10.08 21.94 10.09 22.11L10.1 23.74L13.08 21.61C13.84 21.07 14.69 20.7999 15.63 20.7999H19.32C19.61 20.7999 19.89 20.77 20.16 20.72C20.44 20.67 20.71 20.59 20.97 20.4799C21.23 20.3699 21.48 20.24 21.72 20.09C21.95 19.94 22.17 19.76 22.37 19.57C22.57 19.3699 22.75 19.16 22.91 18.93C23.07 18.7 23.2 18.46 23.31 18.2C23.41 17.95 23.5 17.68 23.55 17.41C23.61 17.14 23.63 16.87 23.63 16.59V12.94C23.63 12.79 23.66 12.64 23.72 12.5C23.78 12.36 23.87 12.23 23.98 12.13C24.09 12.02 24.22 11.93 24.36 11.88C24.51 11.82 24.66 11.79 24.82 11.79C24.97 11.79 25.12 11.82 25.27 11.88C25.41 11.93 25.54 12.02 25.65 12.13C25.76 12.23 25.85 12.36 25.91 12.5C25.97 12.64 26 12.79 26 12.94V16.59C26 17.02 25.95 17.44 25.87 17.86C25.78 18.28 25.66 18.69 25.49 19.08C25.32 19.48 25.11 19.8499 24.87 20.2099C24.63 20.57 24.35 20.9 24.04 21.2C23.73 21.5 23.39 21.7699 23.03 22.0099C22.67 22.2499 22.28 22.45 21.88 22.61C21.47 22.77 21.06 22.9 20.63 22.9799C20.2 23.07 19.76 23.11 19.32 23.11H16.4C15.47 23.11 14.62 23.3799 13.86 23.9199L9.91 26.74C9.67 26.91 9.39999 27 9.10999 27Z" fill="currentColor"></path>
                </svg>
                <span> 开启新对话</span>
              </button>
            </div>
            <div class="chat-history">
              <a 
                v-for="conversation in conversations" 
                :key="conversation.id" 
                class="history-item"
                :class="{ active: currentConversationId === conversation.id }"
                @click="selectConversation(conversation)"
              >
                <div class="history-content">
                  <div class="history-title">{{ conversation.title || '新对话' }}</div>
                  <div class="history-preview">{{ getLastMessagePreview(conversation) }}</div>
                </div>
                <div class="history-actions">
                  <button class="edit-btn" @click.stop="editConversationName(conversation)">✏️</button>
                  <button class="delete-btn" @click.stop="deleteConversation(conversation)">🗑️</button>
                </div>
              </a>
            </div>
          </div>

        </aside>
        <!-- Chat Area -->
        <section class="chat-area">
          <div class="chat-header">
            <div class="chat-title">
              <h2>{{ currentConversationName || '智能问答' }}</h2>
            </div>
            <div class="chat-controls">
              <button class="control-btn" @click="clearCurrentConversation">
                <span>📋</span>
                清空对话
              </button>
            </div>
          </div>
          
          <div class="chat-messages" ref="chatContainer">
            <div 
              v-for="message in messages" 
              :key="message.id"
              :class="['message', message.role === 'user' ? 'sent' : 'received']"
            >
              <div v-if="message.role === 'assistant'" class="avatar">AI</div>
              <div class="message-content">
                <div class="message-text">
                  {{ message.content }}
                </div>
                <div class="message-time">{{ formatTime(message.created_at) }}</div>
              </div>
              <div v-if="message.role === 'user'" class="avatar">U</div>
            </div>
          </div>
          
          <div class="chat-input-area">
            <div class="input-tools">
              <button class="tool-btn">📎</button>
              <button class="tool-btn">📊</button>
            </div>
            <div class="input-container">
              <textarea 
                class="message-input" 
                placeholder="输入您的问题..." 
                rows="1"
                v-model="newMessage"
                @keydown.enter.exact.prevent="sendMessage"
                @keydown.enter.shift.exact.prevent="newLine"
              ></textarea>
              <button class="send-btn" @click="sendMessage">
                <span>➤</span>
              </button>
            </div>
            <div class="input-footer">
              <span class="hint">按 Enter 发送，Shift + Enter 换行</span>
            </div>
          </div>
        </section>

      </div>
    </main>
  </div>
</template>

<script>
import Header from './Header.vue'

export default {
  name: 'AIChat',
  components: {
    Header
  },
  data() {
    return {
      conversations: [],
      // 设置一个初始的临时ID，确保不会是null
      currentConversationId: 'temp-' + Date.now(),
      currentConversationName: '',
      messages: [],
      newMessage: '',
      userId: null,
      // 会话创建状态跟踪
      isCreatingConversation: false
    };
  },
  async mounted() {
    try {
      await this.fetchUserInfo();
      // 确保用户信息获取成功后再获取会话列表
      if (this.userId) {
        await this.fetchConversations();
      } else {
        console.error('用户信息获取失败，无法加载会话');
        // 即使获取用户信息失败，也要保持currentConversationId不为null
        if (!this.currentConversationId || 
            this.currentConversationId === 'undefined' || 
            this.currentConversationId === 'null' || 
            this.currentConversationId.toString().trim() === '') {
          this.currentConversationId = 'temp-' + Date.now();
        }
      }
      this.scrollToBottom();
    } catch (error) {
      console.error('组件初始化失败:', error);
      // 即使初始化失败，也要保持currentConversationId不为null
      if (!this.currentConversationId || 
          this.currentConversationId === 'undefined' || 
          this.currentConversationId === 'null' || 
          this.currentConversationId.toString().trim() === '') {
        this.currentConversationId = 'temp-' + Date.now();
      }
    }
  },
  methods: {
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.chatContainer;
        if (container) {
          container.scrollTop = container.scrollHeight;
        }
      });
    },
    
    async fetchUserInfo() {
      try {
        const token = localStorage.getItem('access_token');
        if (!token) {
          this.$router.push('/');
          return;
        }

        const response = await fetch('http://localhost:8000/api/users/me', {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          }
        });

        if (response.ok) {
          const userData = await response.json();
          this.userId = userData.id;
        } else {
          this.$router.push('/');
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        this.$router.push('/');
      }
    },
    
    async fetchConversations() {
      if (!this.userId) {
        console.warn('用户ID无效，无法获取会话列表');
        return;
      }
      
      try {
        const token = localStorage.getItem('access_token');
        if (!token) {
          console.warn('未找到访问令牌');
          return;
        }
        
        const response = await fetch(`http://localhost:8000/api/conversations/user/${this.userId}`, {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          }
        });
        
        if (response.ok) {
          this.conversations = await response.json();
          console.log('获取到会话列表:', this.conversations.length);
          
          // 如果没有会话，创建一个新会话
          if (this.conversations.length === 0) {
            console.log('没有会话，创建新会话');
            await this.createNewConversation();
          } 
          // 如果有会话但当前没有选中会话，选择第一个会话
          else if (!this.currentConversationId || 
                   this.currentConversationId === 'undefined' || 
                   this.currentConversationId === 'null' || 
                   this.currentConversationId.toString().trim() === '') {
            console.log('选择第一个会话');
            this.selectConversation(this.conversations[0]);
          }
        } else {
          const errorText = await response.text();
          console.error('获取会话列表失败，状态码:', response.status, '错误信息:', errorText);
          // 即使获取失败，也确保有一个默认会话
          if (!this.currentConversationId || 
              this.currentConversationId === 'undefined' || 
              this.currentConversationId === 'null' || 
              this.currentConversationId.toString().trim() === '') {
            this.currentConversationId = 'temp-' + Date.now();
          }
        }
      } catch (error) {
        console.error('获取会话列表失败:', error);
        // 网络错误时也确保有一个默认会话
        if (!this.currentConversationId || 
            this.currentConversationId === 'undefined' || 
            this.currentConversationId === 'null' || 
            this.currentConversationId.toString().trim() === '') {
          this.currentConversationId = 'temp-' + Date.now();
        }
      }
    },
    
    async createNewConversation() {
      // 防止重复调用
      if (this.isCreatingConversation) {
        console.log('已有会话创建操作正在进行中');
        return;
      }
      
      if (!this.userId) {
        await this.fetchUserInfo(); // 确保有用户ID
        if (!this.userId) {
          console.error('无法获取用户信息');
          return;
        }
      }
      
      try {
        this.isCreatingConversation = true;
        const token = localStorage.getItem('access_token');
        console.log('准备创建新会话，用户ID:', this.userId);
        
        if (!token) {
          console.error('未找到访问令牌');
          throw new Error('未找到访问令牌');
        }
        
        const response = await fetch('http://localhost:8000/api/conversations', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            user_id: this.userId
          })
        });
        
        if (response.ok) {
          const newConversation = await response.json();
          console.log('新会话创建成功，返回的会话对象:', newConversation);
          
          // 确保newConversation.id存在
          if (newConversation && newConversation.id) {
            // 确保新会话正确添加到数组开头
            this.conversations = [newConversation, ...this.conversations];
                      
            // 如果是第一个会话，自动选择它
            if (this.conversations.length === 1) {
              this.selectConversation(newConversation);
            }
            // 立即设置当前会话ID和名称
            this.currentConversationId = newConversation.id;
            this.currentConversationName = newConversation.title || '新对话';
            this.messages = []; // 清空消息列表
            console.log('设置当前会话ID:', this.currentConversationId);
            
            // 强制更新组件
            this.$forceUpdate();
          } else {
            console.error('返回的会话对象没有有效的ID:', newConversation);
            throw new Error('服务器返回的会话对象没有有效ID');
          }
        } else {
          const errorText = await response.text();
          console.error('创建会话失败:', response.status, errorText);
          throw new Error(`创建会话失败: ${response.status} ${errorText}`);
        }
      } catch (error) {
        console.error('创建新会话失败:', error);
        // 设置临时会话ID以防止完全失败
        this.currentConversationId = 'temp-' + Date.now();
        this.currentConversationName = '临时对话';
        this.messages = [];
        throw error; // 重新抛出错误，让调用者知道失败了
      } finally {
        this.isCreatingConversation = false;
      }
    },
    
    selectConversation(conversation) {
      if (!conversation || !conversation.id) {
        console.error('无效的会话对象:', conversation);
        return;
      }
      
      // 更新当前会话信息
      this.currentConversationId = conversation.id;
      this.currentConversationName = conversation.title || '新对话';
      this.messages = []; // 立即清空消息列表
      console.log('选择会话:', conversation.id);
      
      // 确保在获取消息前有有效的用户ID
      if (!this.userId) {
        console.warn('用户ID无效，无法获取消息');
        // 如果没有用户ID，尝试获取用户信息后再获取消息
        this.fetchUserInfo().then(() => {
          if (this.userId) {
            this.fetchMessages(conversation.id);
          }
        });
        return;
      }
      
      // 获取会话消息
      this.fetchMessages(conversation.id);
      
      // 强制更新以确保UI正确显示
      this.$nextTick(() => {
        this.$forceUpdate();
        // 确保聊天容器存在后再尝试滚动到底部
        const container = this.$refs.chatContainer;
        if (container) {
          container.scrollTop = container.scrollHeight;
        }
      });
    },
    
    async fetchMessages(conversationId) {
      // 检查conversationId是否有效
      if (!conversationId || 
          conversationId === 'undefined' || 
          conversationId === 'null' || 
          conversationId.toString().trim() === '' ||
          conversationId.toString().startsWith('temp-')) {
        console.warn('无效的会话ID:', conversationId);
        this.messages = []; // 清空消息列表
        return;
      }
      
      // 检查用户ID是否有效
      if (!this.userId) {
        console.warn('用户ID无效，无法获取消息');
        this.messages = [];
        return;
      }
      
      try {
        const token = localStorage.getItem('access_token');
        if (!token) {
          console.warn('未找到访问令牌');
          this.messages = [];
          return;
        }
        
        // 确保URL编码正确
        const encodedConversationId = encodeURIComponent(conversationId);
        const encodedUserId = encodeURIComponent(this.userId);
        
        const response = await fetch(
          `http://localhost:8000/api/conversations/${encodedConversationId}/messages?user_id=${encodedUserId}`, 
          {
            method: 'GET',
            headers: {
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'application/json'
            }
          }
        );
        
        if (response.ok) {
          this.messages = await response.json();
          // 确保每条消息都有created_at字段
          this.messages = this.messages.map(message => ({
            ...message,
            created_at: message.created_at || new Date().toISOString()
          }));
          this.scrollToBottom();
        } else {
          console.error('获取消息失败，状态码:', response.status);
          this.messages = []; // 清空消息列表
        }
      } catch (error) {
        console.error('获取消息失败:', error);
        this.messages = []; // 清空消息列表
      }
    },
    
    async sendMessage() {
      if (!this.newMessage.trim()) {
        console.log('消息为空，不发送');
        return;
      }
      
      // 检查用户ID是否有效
      if (!this.userId) {
        console.error('用户ID无效，无法发送消息');
        alert('用户信息无效，请重新登录');
        return;
      }
      
      // 确保有一个有效的会话ID
      if (!this.currentConversationId || 
          this.currentConversationId === 'undefined' || 
          this.currentConversationId === 'null' ||
          this.currentConversationId.toString().trim() === '' ||
          this.currentConversationId.toString().startsWith('temp-')) {
        console.log('当前没有有效会话或使用临时会话，创建新会话');
        try {
          await this.createNewConversation();
        } catch (error) {
          console.error('创建会话失败:', error);
          alert('无法创建会话，请重试');
          return;
        }
        
        // 再次检查是否成功创建了会话
        if (!this.currentConversationId || 
            this.currentConversationId === 'undefined' || 
            this.currentConversationId === 'null' ||
            this.currentConversationId.toString().trim() === '' ||
            this.currentConversationId.toString().startsWith('temp-')) {
          console.error('无法创建有效会话');
          alert('无法创建会话，请重试');
          return;
        }
      }
      
      console.log('准备发送消息，会话ID:', this.currentConversationId, '用户ID:', this.userId);
      
      const userMessage = {
        role: 'user',
        content: this.newMessage,
        conversation_id: this.currentConversationId,
        created_at: new Date().toISOString()
      };
      
      // 添加用户消息到界面
      this.messages.push(userMessage);
      const messageToSend = this.newMessage;
      this.newMessage = '';
      this.scrollToBottom();
      
      try {
        const token = localStorage.getItem('access_token');
        if (!token) {
          console.error('未找到访问令牌');
          alert('请重新登录');
          return;
        }
        
        console.log('发送API请求到 http://localhost:8000/api/chat');
        
        // 修复请求格式，确保符合后端API要求
        const requestBody = {
          messages: [{ 
            role: 'user', 
            content: messageToSend 
          }],
          user_id: this.userId,
          conversation_id: this.currentConversationId
        };
        
        console.log('请求体:', JSON.stringify(requestBody, null, 2));
        
        const response = await fetch('http://localhost:8000/api/chat', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json',
            'Accept': 'text/event-stream'
          },
          body: JSON.stringify(requestBody)
        });
        
        console.log('API响应状态:', response.status, response.statusText);
        
        if (response.ok) {
          // 处理流式响应
          const reader = response.body.getReader();
          const decoder = new TextDecoder('utf-8');
          let aiMessage = {
            role: 'assistant',
            content: '',
            conversation_id: this.currentConversationId,
            created_at: new Date().toISOString()
          };
          this.messages.push(aiMessage);
          let aiMessageIndex = this.messages.length - 1;
          
          try {
            while (true) {
              const { done, value } = await reader.read();
              if (done) break;
              
              const chunk = decoder.decode(value, { stream: true });
              // 处理可能的多行数据
              const lines = chunk.split('\n\n');
              for (const line of lines) {
                if (line.startsWith('data: ')) {
                  try {
                    const data = JSON.parse(line.slice(6));
                    if (data.response) {
                      // 更新AI消息内容
                      this.messages[aiMessageIndex].content += data.response;
                      this.scrollToBottom();
                    }
                  } catch (e) {
                    // 如果不是JSON格式，可能是纯文本响应
                    const text = line.slice(6);
                    if (text) {
                      this.messages[aiMessageIndex].content += text;
                      this.scrollToBottom();
                    }
                    console.warn('Error parsing SSE data:', e);
                  }
                } else if (line.trim() !== '') {
                  // 处理没有"data: "前缀的情况
                  try {
                    const data = JSON.parse(line);
                    if (data.response) {
                      this.messages[aiMessageIndex].content += data.response;
                      this.scrollToBottom();
                    }
                  } catch (e) {
                    // 如果是纯文本，直接添加
                    if (line.trim()) {
                      this.messages[aiMessageIndex].content += line;
                      this.scrollToBottom();
                    }
                  }
                }
              }
            }
          } catch (streamError) {
            console.error('读取流时出错:', streamError);
          } finally {
            // 确保流被关闭
            try {
              reader.releaseLock();
            } catch (e) {
              console.warn('释放读取器锁时出错:', e);
            }
          }
          this.scrollToBottom();
        } else {
          // 处理错误响应，提供更详细的错误信息
          let errorMessage = '抱歉，我无法处理您的请求。请稍后再试。';
          if (response.status === 422) {
            errorMessage = '请求格式错误，请检查您的输入并重试。';
          } else if (response.status === 401) {
            errorMessage = '认证失败，请重新登录。';
          } else if (response.status === 500) {
            errorMessage = '服务器内部错误，请稍后再试。';
          } else {
            errorMessage = `请求失败 (${response.status}): ${response.statusText}`;
          }
          
          // 尝试获取详细的错误信息
          try {
            const errorData = await response.json();
            if (errorData.detail) {
              errorMessage += ' 详细信息: ' + JSON.stringify(errorData.detail);
            }
          } catch (e) {
            // 无法解析错误详情，使用响应文本
            try {
              const errorText = await response.text();
              if (errorText) {
                errorMessage += ' 详细信息: ' + errorText;
              }
            } catch (e2) {
              // 忽略错误
            }
          }
          
          const aiMessage = {
            role: 'assistant',
            content: errorMessage,
            conversation_id: this.currentConversationId,
            created_at: new Date().toISOString()
          };
          this.messages.push(aiMessage);
          this.scrollToBottom();
        }
      } catch (error) {
        console.error('发送消息失败:', error);
        const errorMessage = {
          role: 'assistant',
          content: '网络错误，请检查您的连接后重试。错误信息: ' + (error.message || error.toString()),
          conversation_id: this.currentConversationId,
          created_at: new Date().toISOString()
        };
        this.messages.push(errorMessage);
        this.scrollToBottom();
      }
    },
    
    newLine() {
      this.newMessage += '\n';
    },
    
    async deleteConversation(conversation) {
      if (!conversation) return;
      
      if (confirm('确定要删除这个会话吗？此操作不可恢复。')) {
        try {
          const token = localStorage.getItem('access_token');
          const response = await fetch(`http://localhost:8000/api/conversations/${conversation.id}?user_id=${this.userId}`, {
            method: 'DELETE',
            headers: {
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'application/json'
            }
          });
          
          if (response.ok) {
            // 从列表中移除会话
            const index = this.conversations.findIndex(c => c.id === conversation.id);
            if (index !== -1) {
              this.conversations.splice(index, 1);
            }
            
            // 如果删除的是当前会话，选择另一个会话或创建新会话
            if (this.currentConversationId === conversation.id) {
              if (this.conversations.length > 0) {
                this.selectConversation(this.conversations[0]);
              } else {
                await this.createNewConversation();
              }
            }
          } else {
            console.error('删除会话失败:', response.status);
          }
        } catch (error) {
          console.error('删除会话失败:', error);
        }
      }
    },
    
    async editConversationName(conversation) {
      const newName = prompt('请输入新的会话名称:', conversation.title || '');
      if (newName !== null && newName !== conversation.title) {
        try {
          const token = localStorage.getItem('access_token');
          const response = await fetch(`http://localhost:8000/api/conversations/${conversation.id}/name`, {
            method: 'PUT',
            headers: {
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              name: newName,
              user_id: this.userId
            })
          });
          
          if (response.ok) {
            conversation.title = newName;
            if (this.currentConversationId === conversation.id) {
              this.currentConversationName = newName;
            }
          }
        } catch (error) {
          console.error('更新会话名称失败:', error);
        }
      }
    },
    
    async clearCurrentConversation() {
      if (!this.currentConversationId || !this.userId) return;
      
      // 检查会话ID是否有效
      if (!this.currentConversationId || this.currentConversationId === 'undefined') {
        alert('会话无效，请刷新页面或重新登录');
        return;
      }
      
      if (confirm('确定要清空当前对话吗？')) {
        try {
          const token = localStorage.getItem('access_token');
          const response = await fetch(`http://localhost:8000/api/conversations/${this.currentConversationId}/messages?user_id=${this.userId}`, {
            method: 'DELETE',
            headers: {
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'application/json'
            }
          });
          
          if (response.ok) {
            // 清空前端消息
            this.messages = [];
          } else {
            console.error('清空对话失败:', response.status);
            // 即使后端失败，也清空前端显示
            this.messages = [];
          }
        } catch (error) {
          console.error('清空对话失败:', error);
          // 即使网络错误，也清空前端显示
          this.messages = [];
        }
      }
    },
    
    getLastMessagePreview(conversation) {
      // 如果当前会话中有消息，返回最后一条消息的预览
      if (this.currentConversationId === conversation.id && this.messages.length > 0) {
        const lastMessage = this.messages[this.messages.length - 1];
        return lastMessage.content.substring(0, 30) + (lastMessage.content.length > 30 ? '...' : '');
      }
      
      // 如果没有加载消息，返回默认文本
      return '新对话';
    },
    
    formatTime(timestamp) {
      // 简单的时间格式化
      if (!timestamp) return '';
      const date = new Date(timestamp);
      return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    }
  }
};
</script>

<style scoped>
.app-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

/* 添加 Header 容器的样式 */
.app-container > :first-child {
  flex-shrink: 0;
}

.main-container {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.content-wrapper {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* Left Sidebar */
.sidebar {
  width: 280px;
  background: white;
  border-right: 1px solid #e1e5e9;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.sidebar-section {
  padding: 20px;
  border-bottom: 1px solid #e1e5e9;
}

.sidebar-section:last-child {
  border-bottom: none;
}

.sidebar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.sidebar-title {
  font-size: 0.9rem;
  color: #6c757d;
  margin: 0;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.add-conversation-btn {
  background: linear-gradient(135deg, #4A90E2, #764ba2);
  color: white;
  border: none;
  cursor: pointer;
  width: -moz-fit-content;
  height: 44px;
  border-radius: 14px;
  flex-shrink: 0;
  align-items: center;
  width: fit-content;
  margin: 0 2px 0 14px;
  font-size: 16px;
  font-weight: 500;
  line-height: 20px;
  display: flex;
  transition: background 0.3s ease;
  align-items: center;
  padding: 0 10px;
  display: flex;
}

.add-conversation-btn span {
  margin-left: 5px;

}

.add-conversation-btn:hover {
  background: linear-gradient(135deg, #3a7bc8, #5a3a8c);
}

.menu-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 15px;
  border-radius: 8px;
  text-decoration: none;
  color: #2c3e50;
  margin-bottom: 5px;
  transition: all 0.3s ease;
}

.menu-item:hover {
  background-color: #f8f9fa;
}

.menu-item.active {
  background-color: #e3f2fd;
  color: #1976d2;
  font-weight: 500;
}

.menu-icon {
  font-size: 1.2rem;
}

.chat-history {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.history-item {
  display: flex;
  justify-content: space-between;
  padding: 12px;
  border-radius: 8px;
  text-decoration: none;
  color: inherit;
  transition: background-color 0.3s ease;
  cursor: pointer;
}

.history-item:hover {
  background-color: #f8f9fa;
}

.history-item.active {
  background-color: #e3f2fd;
}

.history-content {
  flex: 1;
  min-width: 0; /* 允许文本截断 */
}

.history-title {
  font-weight: 500;
  margin-bottom: 5px;
  font-size: 0.95rem;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.history-preview {
  font-size: 0.85rem;
  color: #6c757d;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.history-actions {
  display: flex;
  gap: 5px;
  align-self: flex-start;
}

.edit-btn, .delete-btn {
  border: none;
  background: none;
  cursor: pointer;
  padding: 2px;
  font-size: 0.8rem;
  opacity: 0.5;
  transition: opacity 0.2s;
}

.history-item:hover .edit-btn,
.history-item:hover .delete-btn {
  opacity: 1;
}

/* Chat Area */
.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e1e5e9;
  background: white;
}

.chat-title h2 {
  margin: 0 0 5px 0;
  font-size: 1.5rem;
  color: #2c3e50;
}

.chat-title p {
  margin: 0;
  color: #6c757d;
  font-size: 0.9rem;
}

.control-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 15px;
  border-radius: 6px;
  border: 1px solid #e1e5e9;
  background: white;
  cursor: pointer;
  color: #2c3e50;
  transition: all 0.3s ease;
}

.control-btn:hover {
  background: #f8f9fa;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: #f8f9fa;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.message {
  display: flex;
  gap: 15px;
  max-width: 85%;
}

.message.received {
  align-self: flex-start;
}

.message.sent {
  align-self: flex-end;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  flex-shrink: 0;
}

.message.received .avatar {
  background: linear-gradient(135deg, #4A90E2, #764ba2);
  color: white;
}

.message.sent .avatar {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
}

.message-content {
  display: flex;
  flex-direction: column;
}

.message.received .message-content {
  align-items: flex-start;
}

.message.sent .message-content {
  align-items: flex-end;
}

.message-text {
  padding: 15px;
  border-radius: 18px;
  line-height: 1.5;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  white-space: pre-wrap;
  word-wrap: break-word;
}

.message.received .message-text {
  background: white;
  border-top-left-radius: 5px;
  color: #2c3e50;
}

.message.sent .message-text {
  background: #1976d2;
  border-top-right-radius: 5px;
  color: white;
}

.message-time {
  font-size: 0.75rem;
  margin-top: 5px;
  color: #6c757d;
}

.message.sent .message-time {
  color: #6c757d;
  align-self: flex-end;
}

.chat-input-area {
  padding: 20px;
  background: white;
  border-top: 1px solid #e1e5e9;
}

.input-tools {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.tool-btn {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border: 1px solid #e1e5e9;
  background: white;
  cursor: pointer;
  font-size: 1rem;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.tool-btn:hover {
  background: #f8f9fa;
}

.input-container {
  display: flex;
  gap: 10px;
  align-items: flex-end;
}

.message-input {
  flex: 1;
  padding: 15px;
  border: 1px solid #e1e5e9;
  border-radius: 18px;
  resize: none;
  font-family: inherit;
  font-size: 1rem;
  outline: none;
  transition: border-color 0.3s ease;
  max-height: 150px;
}

.message-input:focus {
  border-color: #4A90E2;
}

.send-btn {
  width: 46px;
  height: 46px;
  border-radius: 50%;
  border: none;
  background: #1976d2;
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background 0.3s ease;
}

.send-btn:hover {
  background: #1565c0;
}

.send-btn span {
  /* 逆时针旋转90度 */
  transform: rotate(-90deg);
  font-size: 1.2rem;
}

.input-footer {
  margin-top: 10px;
  text-align: right;
}

.hint {
  font-size: 0.8rem;
  color: #6c757d;
}

/* Right Sidebar */
.sidebar-right {
  width: 320px;
  background: white;
  border-left: 1px solid #e1e5e9;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.knowledge-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.knowledge-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border-radius: 8px;
  text-decoration: none;
  color: inherit;
  transition: background-color 0.3s ease;
}

.knowledge-item:hover {
  background-color: #f8f9fa;
}

.knowledge-icon {
  font-size: 1.5rem;
}

.knowledge-info {
  flex: 1;
}

.knowledge-title {
  font-weight: 500;
  margin-bottom: 3px;
  font-size: 0.95rem;
}

.knowledge-meta {
  font-size: 0.8rem;
  color: #6c757d;
}

.system-info {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.info-item {
  display: flex;
  justify-content: space-between;
}

.info-label {
  color: #6c757d;
  font-size: 0.9rem;
}

.info-value {
  font-weight: 500;
  font-size: 0.9rem;
}

.info-value.success {
  color: #27AE60;
}

@media (max-width: 1200px) {
  .sidebar-right {
    display: none;
  }
}

@media (max-width: 768px) {
  .sidebar {
    display: none;
  }
  
  .content-wrapper {
    flex-direction: column;
  }
  
  .chat-header {
    padding: 15px;
  }
  
  .chat-messages {
    padding: 15px;
  }
  
  .chat-input-area {
    padding: 15px;
  }
  
  .message {
    max-width: 90%;
  }
}
</style>